#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/22  20:09
# @Author: 余浪人
# @email: yulangren520@gmail.com
import requests, base64, os, json
from datetime import datetime
from flask_login import login_required
from flask_mail import Message, Mail
from apps.control import sys_bp
from Crypto.PublicKey import RSA
from Crypto import Random
from flask import render_template, request, jsonify, current_app, abort
from apps.forms.synthesize_form import TL_Connector_Form, TL_WebApp_Form, TL_Email_Form, TL_Indexes_Form, TL_ThemePush_Form
from apps.lib.cache_sys import cache
from apps.lib.token import generate_token, Verify_authorization
from apps.models.content_model import TL_Content_Model
from apps.models.synthesize_model import TL_Connector_Model, TL_WebApp_Model, db, TL_Indexes_Model, TL_ThemePush_Model
from apps.lib.public import edit_data, get_uuid32, errors, check_obj, add_data, del_not_day30
from apps.models.system_model import TL_Email_Model, TL_Validation_Model


# 接口管理
@sys_bp.route('/connector', endpoint='connector', methods=['GET', 'POST'])
@login_required
def connector():
    conn = TL_Connector_Model.query.filter().first()
    webapp = TL_WebApp_Model.query.filter().first()
    if request.method == 'POST':
        if request.form.get('verify'):
            code = generate_token(request.form.get('public_key'))[-52:]
            rsa = RSA.generate(1024, Random.new().read)
            private_pem = rsa.exportKey().decode('utf-8')  # len > 886
            public_pem = rsa.publickey().exportKey().decode('utf-8')  # len > 271
            return edit_data(TL_WebApp_Form, TL_WebApp_Model, db, webapp.id,
                             {"private_code": code, 'public_pem': public_pem, 'private_pem': private_pem})  # 前台接口
        return edit_data(TL_Connector_Form, TL_Connector_Model, db, conn.id, {"impower_code": get_uuid32()})  # 系统API接口
    form = TL_Connector_Form(data=dict(conn))
    form2 = TL_WebApp_Form(data=dict(webapp))
    return render_template('system_template/connector.html', form=form, form2=form2)


# 站长工具
@sys_bp.route('/tool', endpoint='tool', methods=['GET'])
@login_required
def tool():
    form1 = TL_Indexes_Form(data=dict(TL_Indexes_Model.query.filter_by().first()))
    return render_template('system_template/tools.html', form={'indexes': form1})


# 邮件发送
@sys_bp.route('/email_send', endpoint='email_send', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def email_send():
    form = TL_Email_Form(request.form)
    if request.method == 'POST':
        try:
            if form.validate():
                email_obj = TL_Email_Model.query.first()
                current_app.config.update(
                    DEBUG=False,
                    MAIL_SERVER=email_obj.MAIL_SERVER,
                    MAIL_PROT=email_obj.MAIL_PROT,
                    MAIL_USE_TLS=True,
                    MAIL_USE_SSL=True if email_obj.MAIL_USE_SSL else False,
                    MAIL_USERNAME=email_obj.MAIL_USERNAME,
                    MAIL_PASSWORD=email_obj.MAIL_PASSWORD,
                )
                msg = Message(form.email_title.data, sender=email_obj.MAIL_USERNAME, recipients=[form.email_addressee.data])
                msg.html = form.email_content.data
                mail = Mail(current_app)
                mail.send(msg)
                return jsonify({"status": 0, 'msg': '发送成功'})
            return jsonify({"status": 1, "msg": errors(form)})
        except:
            return jsonify({"status": 1, "msg": "发送错误,请确认配置正确!"})
    return render_template('system_template/email.html', form=form)


# 清空缓存
@sys_bp.route('/emptyCache', endpoint='emptyCache', methods=['POST'])
@login_required
def emptyCache():
    cache.clear()
    del_not_day30('tl_visit_num')
    return jsonify({"status": 0})


# 本地授权验证
@sys_bp.route('/validation_authorization', endpoint='validation_authorization', methods=['GET'])
@login_required
def validation_authorization():
    v = TL_Validation_Model.query.order_by(TL_Validation_Model.id.desc()).filter_by().first()
    if v:
        try:
            response = requests.post(base64.b64decode(b'aHR0cDovL3d3dy50bGNtcy5uZXQvYXV0aGVudGljYXRpb24=').decode(),
                                     data={'domain': request.host_url, 'auth_code': v.v_code})
            if response.status_code == 200 and response.json()['status'] == 0:
                return jsonify({'status': 0})
            elif response.status_code == 200 and response.json()['status'] != 0:
                return jsonify({'status': 1, 'msg': response.json()['msg']})
        except:
            pass
        return jsonify({'status': 2, 'msg': base64.b64decode(b'5o6I5p2D5aSx6LSlLOi/nuaOpeaOiOadg+acjeWKoeWZqOWksei0pSE=').decode()})
    return jsonify({'status': -1})


# 远程授权验证
@sys_bp.route('/tl_sys_validation_authorization', endpoint='tl_sys_validation_authorization', methods=['SELECT'])
@login_required
def save_validation_authorization():
    try:
        code = request.form.get('auth_code')
        response = requests.post(base64.b64decode(b'aHR0cDovL3d3dy50bGNtcy5uZXQvYXV0aGVudGljYXRpb24=').decode(),
                                 data={'domain': request.host_url, 'auth_code': code})
        try:
            if response.status_code == 200 and response.json()['status'] == 0:
                obj = TL_Validation_Model()
                obj.set_attrs({'v_code': code})
                db.session.add(obj)
                db.session.commit()
                return jsonify({'status': 0, 'msg': base64.b64decode(b'5oGt5Zac5oKoLOiOt+W+l1RM5a6Y5pa55o6I5p2D5oiQ5YqfIQ==').decode()})
            elif response.status_code == 200 and response.json()['status'] != 0:
                return jsonify({'status': 1, 'msg': response.json()['msg']})
        except:
            db.session.rollback()
            return jsonify({'status': 3, 'msg': base64.b64decode(b'5o6I5p2D5aSx6LSl5byC5bi4LOivt+iBlOezu+W8gOWPkeiAhSE=').decode()})
    except:
        pass
    return jsonify({'status': 2, 'msg': base64.b64decode(b'5o6I5p2D5aSx6LSlLOi/nuaOpeaOiOadg+acjeWKoeWZqOWksei0pSE=').decode()})


# 百度索引提交
@sys_bp.route('/indexes', endpoint='indexes', methods=['POST', 'UPDATE'])
@login_required
def indexes():
    # 验证保存
    form = TL_Indexes_Form(request.form)
    try:
        obj = TL_Indexes_Model.query.filter_by().first()
        if form.validate() and not check_obj(obj):
            obj.set_attrs(form.data)
            db.session.commit()
        else:
            return jsonify({"status": 1, "msg": errors(form)})
    except:
        db.session.rollback()
        return jsonify({"status": 1, "msg": errors(form)})
    if request.method == 'POST':
        headers = {'User-Agent': 'curl/7.12.1', 'Host': 'data.zz.baidu.com', 'Content-Type': 'text/plain'}
        contentList = TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,
                                                                                         TL_Content_Model.update_time < datetime.now()).all()[
                      :int(form.indexes_num.data)]
        data = [f'{form.indexes_design.data}'.replace('[*tl-did*]', obj.uuid) for obj in contentList]
        if not len(data): return jsonify({'status': 1, 'msg': '未获取到参数,请添加内容'})
        response = requests.post(form.push_address.data, data='\n'.join(data), headers=headers)
        if response.status_code == 200:
            return jsonify({'status': 0, 'msg': '百度索引提交成功!'})
        return jsonify({'status': 4, 'msg': f'提交失败{response.json()["message"]}({response.json()["error"]})'})
    return jsonify({'status': 0, 'msg': '保存成功'})


# 模板主题中心
@sys_bp.route('/templates_theme', endpoint='templates_theme', methods=['GET', 'POST', 'UNLOAD'])
@login_required
def templates_theme():
    if request.method == 'POST':
        theme_id = request.form.get('theme_id', '')
        current = TL_ThemePush_Model.query.filter_by(uuid=theme_id).first()
        if check_obj(current): pass
        theme_list = TL_ThemePush_Model.query.filter().all()
        for theme in theme_list: theme.set_attrs({'is_current': 0})
        try:
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({'status': 1, 'msg': '应用模板失败'})
        try:
            current.set_attrs({'is_current': 1})
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({'status': 1, 'msg': '应用模板失败'})
        cache.clear()
        return jsonify({'status': 0})
    elif request.method == 'UNLOAD':
        theme_id = request.form.get('theme_id', '')
        current = TL_ThemePush_Model.query.filter_by(uuid=theme_id).first()
        if check_obj(current): pass
        db.session.delete(current)
        try:
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({'status': 1, 'msg': '卸载模板失败'})
        return jsonify({'status': 0, 'msg': '卸载模板成功'})
    current = TL_ThemePush_Model.query.filter_by(is_current=1).first()
    theme_list = TL_ThemePush_Model.query.filter().all()
    theme_path = f'{os.getcwd()}/apps/templates/web_template'.replace('\\', '/')
    try:
        with open(f'{theme_path}/{current.identifier}/info.json', 'r', encoding='utf-8') as fp:
            info = json.loads(fp.read())
    except:
        return abort(404)
    info.update({'theme_id': current.uuid})
    current_theme = {'info': info}
    themes = []
    for theme in theme_list:
        try:
            if os.path.isfile(f'{theme_path}/{theme.identifier}/info.json'):
                with open(f'{theme_path}/{theme.identifier}/info.json', 'r', encoding='utf-8') as fp:
                    data = json.loads(fp.read())
                    data.update({'theme_id': theme.uuid})
                    themes.append(data)
        except:
            pass
    return render_template('system_template/templates_theme.html', current_theme=current_theme, themes=themes)


# 安装模板
@sys_bp.route('/theme_push', endpoint='theme_push', methods=['GET', 'POST'])
@login_required
def theme_push():
    if request.method == 'POST':
        return add_data(TL_ThemePush_Model, TL_ThemePush_Form, db)
    return render_template('system_template/theme_push.html')
